package com.bluedon.ism.sensitive;



import java.util.ArrayList;
import java.util.List;

public class Matcher {
	private Node node;
	private String replaceString;
	private StringBuffer sb;
	private List<Matched> matchedList=new ArrayList<Matched>();
	
	public Matcher(Node node) {
		this.node=node;
	}
	
	public Matcher(Node node,String replaceString) {
		this.node=node;
		this.replaceString=replaceString;
	}
	
	void process(String content) {
		if(content==null)
			return;
		sb=new StringBuffer(content);
		int size=sb.length();
		Node matchNode;
		for(int i=0,j=i;i<size;i++) {
			char c=sb.charAt(i);
			matchNode=Node.findNode(node, c);
			if(matchNode!=null&&matchNode.flag==0) {
				j=i;
				j++;
				while(j<size) {
					c=sb.charAt(j);
					matchNode=Node.findNode(matchNode, c);
					if(matchNode==null)
						break;
					if(matchNode.flag==1) {
						System.out.println(sb.subSequence(i, j+1));
						matchedList.add(new Matched(i, j+1, sb.subSequence(i, j+1).toString()));
						i=j;
						break;
					}
					j++;
				}
			}
		}
	}
	
	public String replace(String str) {
		if(sb!=null&&sb.length()>0) {
			int offset=0;
			int length=sb.length();
			for(Matched m:matchedList) {
				sb.replace(m.start-offset, m.end-offset, str);
				offset=length-sb.length();
			}
			return sb.toString();
		}else {
			return "";
		}
	}
	
	public class Matched {
		public int start;
		public int end;
		public String string;
		
		public Matched(int start, int end, String string) {
			this.start=start;
			this.end=end;
			this.string=string;
		}
	}
}
